package com.ylbh.modules.goodsorder.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylbh.common.exception.NormalException;
import com.ylbh.common.pojo.goodsorder.dto.OrderConditionDTO;
import com.ylbh.common.pojo.goodsorder.vo.*;
import com.ylbh.common.pojo.goodsorder.dto.OrderShipmentDTO;
import com.ylbh.common.utils.*;
import com.ylbh.modules.accessory.entity.HNExpressCallback;
import com.ylbh.modules.accessory.service.HLGoodsService;
import com.ylbh.modules.accessory.service.impl.HLGoodsServiceImpl;
import com.ylbh.modules.goodsorder.entity.ShoppingOrderForm;
import com.ylbh.modules.goodsorder.mapper.ShoppingOrderFormMapper;
import com.ylbh.modules.goodsorder.service.ShoppingOrderFormService;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品订单
 * @author czx
 * @date 2019-04-26 14:47:48
 */
@Service
public class ShoppingOrderFormServiceImpl extends ServiceImpl<ShoppingOrderFormMapper, ShoppingOrderForm> implements ShoppingOrderFormService {

    private final Logger log = LoggerFactory.getLogger(ShoppingOrderFormServiceImpl.class);

    @Autowired
    private ShoppingOrderFormMapper shoppingOrderFormMapper;

    // 订单发货推送
    @Value("${url.deliverGoods}")
    private String deliverGoods;

    @Value("${url.kdniao}")
    private String kdniao;

    @Value("${url.express}")
    private String express;

    @Value("${url.clientOrderSendPushByOpenId}")
    private String clientOrderSendPushByOpenId;

    @Autowired
    private HLGoodsServiceImpl hlGoodsService;

    /**
     * 根据条件来查询出订单列表信息
     * @param orderConditionDTO
     * @return
     */
    @Override
    public PageUtils queryOrderByCondition(OrderConditionDTO orderConditionDTO) {
        Page<Integer> page = new Page<>(orderConditionDTO.getPage(), orderConditionDTO.getLimit());
        List<OrderListVO> order = shoppingOrderFormMapper.selectOrderByCondition(orderConditionDTO, page);
        // 寻找该笔单下的所有商品
        for (OrderListVO o : order) {
            // 订单中申请售后未审核的数量
            int count = shoppingOrderFormMapper.notAuditedCount(o.getOrderId());
            o.setCount(count);
            List<SubOrderListVO> subOrder = shoppingOrderFormMapper.selectSubOrder(o.getId());
            // 如果state为3或者6表示已经申请退款
            // 如果子订单的长度大于issue表示还有别的子订单，显示发货信息
            int issue = 0;
            for (SubOrderListVO sub : subOrder) {
                if (null != sub.getState()) {
                    if (sub.getState() == 3 || sub.getState() == 6) {
                        issue = issue + 1;
                    }
                }
                // 根据子订单的类型的计算消耗积分或赠送积分
//                if (sub.getPayType() == 1) {
//                    o.setPriceType(sub.getPayType());
//                    o.setIntegral(sub.getIntegral() + o.getIntegral());
//                }
//                if (sub.getPayType() == 2) {
//                    o.setPriceType(sub.getPayType());
//                    o.setIntegral(sub.getIntegral() + sub.getGiveIntegral());
//                }
                if (null != o.getMsg() && !StringUtils.isEmpty(o.getMsg())) {
                    sub.setMsg(o.getMsg());
                }
            }
            o.setIssue(issue);
            o.setSubOrder(subOrder);
            // 将收货信息分割成收货人姓名、电话、地址
            if (!StringUtils.isEmpty(o.getDeliveryAddress())) {
                String[] address = o.getDeliveryAddress().split(",,,,,,");
                if (address.length == 3) {
                    o.setAddress(address[2]);
                    o.setConsigneeName(address[0]);
                    o.setPhone(address[1]);
                } else {
                    o.setAddress("");
                    o.setConsigneeName("");
                    o.setPhone("");
                }
            }
        }
        Page<OrderListVO> page1 = new Page<>();
        page1.setTotal(page.getTotal()).setRecords(order);
        return new PageUtils(page1);
    }

    /**
     * 查出所有物流公司
     * @return
     */
    @Override
    public List<LogisticsCompanyVO> queryLogisticsCompany() {
        return shoppingOrderFormMapper.selectLogisticsCompanyVO();
    }

    /**
     * 订单发货
     * @param subOrderListVO
     */
    @Override
    public void modifyOrderShipmentById(String id, String shipId, String shipCode, String cartId, String userId, String orderId) {
//        orderShipmentDTO.setDate(new Date());
//        shoppingOrderFormMapper.updateOrderShipmentById(orderShipmentDTO);
        String[] shipIds = shipId.split(",");
        String[] shipCodes = shipCode.split(",");
        String[] cartIds = cartId.split(",");
        Date date = new Date();
        String expressId = "";
        String expressNO = "";
        int len = cartIds.length - 1;
        for (int j = 1; j < cartIds.length; j++) {
            shoppingOrderFormMapper.updateGoodsCartInfoDeliveryNo(cartIds[j], shipIds[j],
                                                                  shipCodes[j], date);
            if (len == j) {
                shoppingOrderFormMapper.updateOrderFormInfoShipCode(id, shipIds[j], shipCodes[j], date);
                expressId = shipIds[j];
                expressNO = shipCodes[j];
            }
        }
        // 给用户推送发货通知
        Map<String, String> map = new HashMap<>();
        map.put("userId", userId);
        map.put("data", id);
        map.put("type", "9");
        map.put("stateStr", "已发货");
        map.put("froms", "");
        map.put("pushContent", "");
        HttpClientHelperUtils.sendHttpPosts(deliverGoods, map);

        // 发货对接快递鸟开始
        HashMap<String, String> map1 = new HashMap<>();
        // 根据物流公司的id去查询编码
        String expressCode = shoppingOrderFormMapper.selectExpressCode(shipIds[1]);
        // 根据订单查询收货地址id
//        String addressId = shoppingOrderFormMapper.selectAddressId(id);
        AddressVO addressVO = shoppingOrderFormMapper.selectAddress(id);
        map1.put("shipperCode", expressCode);
        map1.put("logisticCode", shipCodes[1]);
        map1.put("orderCode", orderId);
        map1.put("receiptName", addressVO.getTrueName());
        map1.put("receiptMobile", addressVO.getMobile());
        map1.put("receiptProvinceName", addressVO.getProvince());
        map1.put("receiptCityName", addressVO.getCity());
        map1.put("receiptExpAreaName", addressVO.getArea());
        map1.put("receiptAddress", addressVO.getAreaInfo());
        map1.put("senderName", null);
        map1.put("senderMobile", null);
        map1.put("senderProvinceName", null);
        map1.put("senderCityName", null);
        map1.put("senderExpAreaName", null);
        map1.put("senderAddress", null);
        map1.put("goodsName", shoppingOrderFormMapper.selectGoodsName(cartIds[1]));
        String s = HttpClientHelperUtils.sendHttpPost(kdniao, map1);
        log.info("============================快递鸟返回信息：" + s);

        // 根据物流公司匹配到物流公司名
        List<LogisticsCompanyVO> expressList = queryLogisticsCompany();
        if (null != expressList) {
            for (LogisticsCompanyVO vo:expressList) {
                if (vo.getId().toString().equals(expressId)) {
                    expressId = vo.getCompanyName();
                    break;
                }
            }
        }

        // 发货微信公众号推送
        Map<String, String> map2 = new HashMap<>();
        map2.put("addressInfo", addressVO.getProvince() + addressVO.getCity() + addressVO.getArea() +addressVO.getAreaInfo());
        map2.put("expressName", expressId);
        map2.put("expressNo", expressNO);
        map2.put("openId", "");
        map2.put("orderNo", orderId);
        map2.put("sendTime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        map2.put("userId", userId);
        String s1 = HttpClientHelperUtils.sendHttpPosts(clientOrderSendPushByOpenId, map2);
        log.info("============================订单发货公众号通知：" + s1);
//        int index = subOrderListVO.size();
//        if (subOrderListVO.size() > 0) {
//
//            for (int i = 0; i < subOrderListVO.size(); i++) {
//                // 表示是最后一个订单，则把信息写到总订单表中
//                shoppingOrderFormMapper.updateGoodsCartInfoDeliveryNo(subOrderListVO.get(i).getCartId(), subOrderListVO.get(i).getShipCodeId(),
//                                                         subOrderListVO.get(i).getShipCodeNum(), date);
//                if (i == index) {
//                    shoppingOrderFormMapper.updateOrderFormInfoShipCode(id, subOrderListVO.get(i).getShipCodeId(), subOrderListVO.get(i).getShipCodeNum(), date);
//                }
//            }
//        }
    }

    /**
     * 根据物流单号来查询物流记录
     * @param logisticsNumber
     * @return
     * @throws Exception
     */
    @Override
    public LogisticsInformationVO getLogisticsInformationByExpressNo(String expressNo) throws Exception {
//        String resultString;
//        HashMap map = new HashMap();
//        map.put("expressNo",expressNo);
//        HashMap map1 = new HashMap();
//        map1.put("Accept", "*/*");
//        map1.put("Connection", "Keep-Alive");
//        map1.put("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)");
//        HttpResponse response = HttpUtils.doGet("https://api.yilianbaihui.cn/","app/order/getExpressInfoByExpressNo","GET",
//                map1,map);
//        LogisticsInformationVO vo = new LogisticsInformationVO();
//        if(response.getStatusLine().getStatusCode() == 200){
//            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");//调用getEntity()方法获取到一个HttpEntity实例
//            System.out.println(resultString);
//            JSONObject jsonObject = (JSONObject) JSONObject.parse(resultString);
//            String code = jsonObject.getString("code");
//            if("200".equals(code)){
//                JSONObject jsonDate = jsonObject.getJSONObject("data");
//                JSONArray jsonArray = jsonDate.getJSONArray("list");
//                vo.setExpressNo(jsonDate.getString("no"));//快递单号
//                vo.setExpressName(jsonDate.getString("name"));//快递公司
//                vo.setExpressPhone(jsonDate.getString("phone"));//快递公司电话
//                vo.setSite(jsonDate.getString("site"));//公司网址
//                vo.setList(jsonArray);
//            }
//        }
        HashMap map = new HashMap();
        map.put("expressNo",expressNo);
        LogisticsInformationVO vo = new LogisticsInformationVO();
        String result = HttpClientHelperUtils.sendHttpPost(express, map);
        JSONObject jsonObject = (JSONObject) JSONObject.parse(result);
        if ("200".equals(jsonObject.getString("code"))) {
            JSONObject data = jsonObject.getJSONObject("data");
            vo.setExpressNo(data.getString("logisticCode"));
            vo.setExpressName(data.getString("companyName"));
            vo.setExpressPhone(data.getString("serviceHotline"));
            vo.setList(data.getJSONArray("traces"));
        }
        return vo;
    }

    /**
     * 根据id查出当前该商品的物流公司
     * @param id
     */
    @Override
    public ExpressCompanyVO getExpressNameById(Long id) {
        return shoppingOrderFormMapper.selectExpressNameById(id);
    }

    /**
     * 修改物流
     * @param orderShipmentDTO
     */
    @Override
    public void modifyExpressNameOrShipCodeById(OrderShipmentDTO orderShipmentDTO) {
        shoppingOrderFormMapper.updateExpressNameOrShipCodeById(orderShipmentDTO);
    }

    @Override
    public OrderDetailsVO getOrderByIds(String id) {
        OrderDetailsVO order = shoppingOrderFormMapper.selectOrderByIds(id);
        List<OrderDetailsVO> orderReturn = shoppingOrderFormMapper.selectOrderForm(order.getOrderId());
        if (orderReturn.size() > 0) {
            order.setReturnType(orderReturn.get(0).getReturnType());
            order.setReturnStatus(orderReturn.get(0).getReturnStatus());
            order.setReturnShipTime(orderReturn.get(0).getReturnShipTime());
        }
        if (null != order) {
            if (!StringUtils.isEmpty(order.getDeliveryAddress())) {
                // 根据收货信息把数据切割成收货人、电话、地址
                String[] deliveryAddress = order.getDeliveryAddress().split(",,,,,,");
                if (deliveryAddress.length == 3) {
                    order.setPerson(deliveryAddress[0]);
                    order.setPhone(deliveryAddress[1]);
                    order.setAddress(deliveryAddress[2]);
                }
            }
            // 根据主订单id来查询出关联的子订单来计算出送的券和消耗的券量
            List<GoodsCartVO> cartIds = shoppingOrderFormMapper.selectCartIdById(order.getId());
            // 消耗券数量
            int consumeIntegral = 0;
            // 获得券数量
            int getIntegral = 0;
//            for (GoodsCartVO vo : cartIds) {
//                if (!StringUtils.isEmpty(vo.getSpecItemIds())) {
//                    String[] specIds = vo.getSpecItemIds().split("_");
//                    // 根据商品id查询出对应商品的规格信息
//                    String inventoryDetail = shoppingOrderFormMapper.selectGoodsById(vo.getGoodsId());
//                    List<GoodsSpecVO> specVOList = FastJsonUtil.toList(inventoryDetail, GoodsSpecVO.class);
//                    for (GoodsSpecVO spec : specVOList) {
//                        for (int i = 0; i < specIds.length; i++) {
//                            String specId = specIds[i] + "_";
//                            if (specId.equals(spec.getId())) {
//                                // 兑换商品
//                                if (spec.getPriceType() == 1) {
//                                    consumeIntegral = consumeIntegral + (spec.getIntegral() * vo.getCount());
//                                }
//                                // 福利商品
//                                if (spec.getPriceType() == 2) {
//                                    getIntegral = getIntegral + (spec.getIntegral() * vo.getCount());
//                                }
//                            }
//                        }
//                    }
//                }
//            }
            for (GoodsCartVO vo:cartIds) {
                if (vo.getPriceType() == 1) {
                    consumeIntegral = consumeIntegral + (vo.getIntegral() * vo.getCount());
                }
                if (vo.getIntegral() == 2) {
                    getIntegral = getIntegral + (vo.getGiveIntegral() * vo.getCount());
                }
            }
            order.setConsumeIntegral(consumeIntegral);
            order.setGetIntegral(getIntegral);

            // 订单商品信息
            List<OrderGoodsVO> list = shoppingOrderFormMapper.selectOrderGoodsByOrderId(Long.valueOf(order.getId()));
            order.setList(list);
        }
        return order;
    }

    /**
     * 商城订单详情
     * @param orderId
     * @return
     */
    @Override
    public OrderDetailsVO getOrderById(String orderId) {
        OrderDetailsVO order = shoppingOrderFormMapper.selectOrderById(orderId);
        List<OrderDetailsVO> orderReturn = shoppingOrderFormMapper.selectOrderForm(order.getOrderId());
        if (orderReturn.size() > 0) {
            order.setReturnType(orderReturn.get(0).getReturnType());
            order.setReturnStatus(orderReturn.get(0).getReturnStatus());
            order.setReturnShipTime(orderReturn.get(0).getReturnShipTime());
        }
        if (null != order) {
            if (!StringUtils.isEmpty(order.getDeliveryAddress())) {
                // 根据收货信息把数据切割成收货人、电话、地址
                String[] deliveryAddress = order.getDeliveryAddress().split(",,,,,,");
                if (deliveryAddress.length == 3) {
                    order.setPerson(deliveryAddress[0]);
                    order.setPhone(deliveryAddress[1]);
                    order.setAddress(deliveryAddress[2]);
                }
            }
            // 根据主订单id来查询出关联的子订单来计算出送的券和消耗的券量
            List<GoodsCartVO> cartIds = shoppingOrderFormMapper.selectCartIdById(order.getId());
            // 消耗券数量
            int consumeIntegral = 0;
            // 获得券数量
            int getIntegral = 0;
//            for (GoodsCartVO vo : cartIds) {
//                if (!StringUtils.isEmpty(vo.getSpecItemIds())) {
//                    String[] specIds = vo.getSpecItemIds().split("_");
//                    // 根据商品id查询出对应商品的规格信息
//                    String inventoryDetail = shoppingOrderFormMapper.selectGoodsById(vo.getGoodsId());
//                    List<GoodsSpecVO> specVOList = FastJsonUtil.toList(inventoryDetail, GoodsSpecVO.class);
//                    for (GoodsSpecVO spec : specVOList) {
//                        for (int i = 0; i < specIds.length; i++) {
//                            String specId = specIds[i] + "_";
//                            if (specId.equals(spec.getId())) {
//                                // 兑换商品
//                                if (spec.getPriceType() == 1) {
//                                    consumeIntegral = consumeIntegral + (spec.getIntegral() * vo.getCount());
//                                }
//                                // 福利商品
//                                if (spec.getPriceType() == 2) {
//                                    getIntegral = getIntegral + (spec.getIntegral() * vo.getCount());
//                                }
//                            }
//                        }
//                    }
//                }
//            }
            for (GoodsCartVO vo:cartIds) {
                if (vo.getPriceType() == 1) {
                    consumeIntegral = consumeIntegral + (vo.getIntegral() * vo.getCount());
                }
                if (vo.getIntegral() == 2) {
                    getIntegral = getIntegral + (vo.getGiveIntegral() * vo.getCount());
                }
            }
            order.setConsumeIntegral(consumeIntegral);
            order.setGetIntegral(getIntegral);

            // 订单商品信息
            List<OrderGoodsVO> list = shoppingOrderFormMapper.selectOrderGoodsByOrderId(Long.valueOf(order.getId()));
            order.setList(list);
        }
        return order;
    }

    /**
     * 导出商城订单
     * @param response
     * @param request
     * @throws NormalException
     */
    @Override
    public void orderExcel(HttpServletResponse response, HttpServletRequest request) throws NormalException {
        List<OrderExcelVO> excel = shoppingOrderFormMapper.selectOrderExcel(request.getParameter("orderTypes"), request.getParameter("startTime"), request.getParameter("endTime"), request.getParameter("invoiceType"));
        for (OrderExcelVO vo : excel) {
            if (!StringUtils.isEmpty(vo.getDeliveryAddress())) {
                // 收货人信息
                String[] consignee = vo.getDeliveryAddress().split(",,,,,,");
                if (consignee.length == 3) {
                    vo.setName(consignee[0]);
                    vo.setPhone(consignee[1]);
                    vo.setAddress(consignee[2]);
                }
//                if (!StringUtils.isEmpty(vo.getPriceType()) && "兑换商品".equals(vo.getPriceType())) {
//                    vo.setConsumeIntegral(vo.getIntegral());
//                    vo.setIntegral(0);
//                }else if(!StringUtils.isEmpty(vo.getPriceType()) && "福利商品".equals(vo.getPriceType())) {
//                    vo.setConsumeIntegral(0);
//                }
            }
        }
        ExcelUtils.exportExcel(excel, "商城订单", "", OrderExcelVO.class, System.currentTimeMillis() + ".xls", response);
    }

    /**
     * 子订单发货
     * @param orderShipmentDTO
     */
    @Override
    public String modifyOrderShipmentByCardId(OrderShipmentDTO orderShipmentDTO) {
        // 先要总订单的id来查询，如果这个笔订单有多个子订单
        // 那么在商城订单表中不加入发货状态和物流信息，只在对应的子订单中加入物流信息
        // 如果是该笔订单的最一个子订单发货，就将最后一个发货的信息写到总订单的信息上，并且修改发货状态

        // 先查询出子订单的物流信息
        List<String> deliveryNo = shoppingOrderFormMapper.selectGoodsCartByOfId(orderShipmentDTO.getOrderId());
        if (deliveryNo.size() > 0) {
            int count = 0;
            for (String s : deliveryNo) {
                // 如果子订单中有还没有物流信息的就进行+1操作
                if (null == s || StringUtils.isEmpty(s)) {
                    count = count + 1;
                }
            }

            orderShipmentDTO.setDate(new Date());
            // 如果为1说明是该笔订单里面的最后一个发货的物品,则在总订单信息中写入记录信息
            if (count == 1) {
                // 修改子订单中的信息
                shoppingOrderFormMapper.updateGoodsCartById(orderShipmentDTO);
                // 修改总订单中的信息
                shoppingOrderFormMapper.updateOrderShipmentByIds(orderShipmentDTO);
            } else {
                // 修改子订单中的信息
                shoppingOrderFormMapper.updateGoodsCartById(orderShipmentDTO);
            }

            // 给用户推送发货通知
            Map<String, String> map = new HashMap<>();
            map.put("userId", orderShipmentDTO.getUserId().toString());
            map.put("data", orderShipmentDTO.getOrderId());
            map.put("type", "9");
            map.put("stateStr", "已发货");
            map.put("froms", "");
            map.put("pushContent", "");
            return HttpClientHelperUtils.sendHttpPosts(deliverGoods, map);
        }
        return null;
    }

    /**
     * 修改子订单物流信息
     * @param orderShipmentDTO
     */
    @Override
    public void modifyExpressNameOrDeliveryNoById(OrderShipmentDTO orderShipmentDTO) {
        orderShipmentDTO.setDate(new Date());
        shoppingOrderFormMapper.selectExpressNameOrDeliveryNoById(orderShipmentDTO);
    }

    /**
     * 子订单物流公司
     * @param id
     * @return
     */
    @Override
    public ExpressCompanyVO getExpressNameByCartId(Long id) {
        return shoppingOrderFormMapper.selectExpressNameByCartId(id);
    }

    /**
     * 发货时查出没有售后的订单信息
     * @param id
     * @return
     */
    @Override
    public List<SubOrderListVO> notIssuedGoods(Long id) {
        return shoppingOrderFormMapper.selectSubOrders(id);
    }

    /**
     * 候鸟订单信息发货状态
     */
    @Override
    public void selectHNOrder() {
        List<HNOrderVO> list = shoppingOrderFormMapper.selectHNOrder();
        for (HNOrderVO vo:list) {
            HashMap<String, String> map = new HashMap<>();
            map.put("clientId", "14485");
            map.put("clientToken", "F56msDSaaOsEvp57M2ooubckB1gPnIhN");
            map.put("method", "order.getExpress");
            map.put("cusOrderNo", vo.getOverseasOrderNo());
            String express = HttpUtils.sendPost("http://www.houniao.hk/api/route", map);
            JSONObject jsonObject1 = JSON.parseObject(express);
//            shoppingOrderFormMapper.insertComment(jsonObject1.toString());
//            JSONObject data = jsonObject1.getJSONObject("expressInfo");
            JSONObject[] jsonObject = new JSONObject[]{JSON.parseObject(jsonObject1.toString())};
            List<HNOrderExpressVO> expressList = FastJsonUtil.toList(jsonObject[1].toString(), HNOrderExpressVO.class);
            if (null != expressList) {
                for (int i = 0; i < expressList.size(); i++) {
                    if ("1".equals(expressList.get(i).getOrderStatus())) {
                        HNExpressCallback callback = new HNExpressCallback();
                        callback.setOrderNo(expressList.get(i).getCusOrderNo());
                        callback.setGoodsSku(expressList.get(i).getGoodsSku());
                        callback.setExpressNo(expressList.get(i).getExpressNo());
                        callback.setGoodsSpecNum(expressList.get(i).getGoodsSpecNum());
                        callback.setDeliveryTime(expressList.get(i).getDeliveryTime());
                        callback.setExpressCode(expressList.get(i).getExpressCode());
                        hlGoodsService.hnDeliverGoods(callback);
                    }
                }
            }

        }
    }

    /**
     * 通知供应商发货
     * @param id
     */
    @Override
    public void notifySupplier(String id) {
        shoppingOrderFormMapper.updateNotifySupplier(id, new Date());
    }
}
